package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Dict;
import com.bwie.service.DictService;
import com.bwie.mapper.DictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author lenovo
 * @description 针对表【t_dict(字典表)】的数据库操作Service实现
 * @createDate 2025-03-26 16:25:50
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
        implements DictService {

    @Autowired
    DictMapper dictMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 项目启动时从数据库中读取数据到缓存中
     */
    @PostConstruct
    public void loadDict() {
        System.out.println("加载字典到缓存中");

//        //全量更新
//        List<Dict> dicts = dictMapper.selectList(null);
//        redisTemplate.opsForValue().set("dict", JSON.toJSONString(dicts));


        //增量更新
        List<Dict> dicts = dictMapper.selectList(null);
        for (Dict dict : dicts) {
            Boolean hasKey = redisTemplate.opsForHash().hasKey("dict", dict.getDictId().toString());
            if (!hasKey) {
                redisTemplate.opsForHash().put("dict", dict.getDictId().toString(), JSON.toJSONString(dict));
            }
        }
    }

}




